
#include <ctype.h>

#include "tar.h"
#include "options.h"
#include "dir.h"
#include "args.h"


/* argument routines */


static char **MyArgV,**InitialArgV;


void ResetArgs(void) {
  MyArgV = InitialArgV;
} /* ResetArgs */


void InitArgs(char *argv[]) {
  FILE *ArgFile;
  int ArgCnt,ArgSpace,Length;
  char *Next,*cp;
  char Buffer[256];

  if (UseListFile) {
    ArgFile = fopen(listfile,"r");
    if (ArgFile == NULL) {
      fprintf(stderr,"tar: unable to open list file\n");
      Terminate(24);
    }
    ArgCnt = 0;
    ArgSpace = 0;
    while (fgets(Buffer,256,ArgFile) != NULL) {
      Length = strlen(Buffer);
      if (Length <= 1)
        continue;
      Buffer[Length-1] = '\0';
      if (Buffer[0] == '.') {
        if (Length <= 3)
          Next = NULL;
        else {
          Next = malloc(Length-2);
          strcpy(Next,Buffer+2);
        }
        cp = Buffer+1;
        if (CheckOption(&cp,Next) == 0 && Next != NULL)
          free(Next);
        continue;
      }
      if (ArgCnt+1 >= ArgSpace) {
        ArgSpace += 50;
        InitialArgV = realloc(InitialArgV,ArgSpace*sizeof(char *));
        if (InitialArgV == NULL) {
          fprintf(stderr,"tar: InitialArgV allocation fault\n");
          Terminate(2);
        }
      }
      InitialArgV[ArgCnt] = malloc(Length);
      if (InitialArgV[ArgCnt] == NULL) {
        fprintf(stderr,"tar: argument allocation fault\n");
        Terminate(3);
      }
      strcpy(InitialArgV[ArgCnt],Buffer);
      ArgCnt++;
    }
    InitialArgV = realloc(InitialArgV,ArgCnt*sizeof(char *));
    if (InitialArgV == NULL) {
      fprintf(stderr,"tar: InitialArgV reallocation fault\n");
      Terminate(4);
    }
    InitialArgV[ArgCnt] = NULL;
    fclose(ArgFile);
  } else
    InitialArgV = argv;
  ResetArgs();
} /* InitArgs */


char *GetArg(int Inc) {
  char *Arg;
  
  Arg = *MyArgV;
  MyArgV += Inc;
  return Arg;
} /* GetArg */


static int PrefixMatches(char *s1, char *s2) {
  if (isArchie) {
    while (*s1)
      if (tolower(*s1++) != tolower(*s2++))
        return 0;
  } else {
    while (*s1)
      if (*s1++ != *s2++)
        return 0;
  }
  if (*s2) {
    return (*s2 == (isArchie ? FS_DIRSEP : UNIX_DIRSEP));
  }
  return 1;
} /* PrefixMatches */


int MatchesNextArg(char *startdir) {
  char *cp;
  int None;

  if (ExtractFromArchive) {
#if WITH_PWD
    ChangeCurrentDir(startdir);
#endif
  }
  ResetArgs();
  None = 1;
  while (cp = GetArg(1), cp) {
    if (ExtractFromArchive && !strcmp(cp, "-C") && (cp = GetArg(1), cp)) {
#if WITH_PWD
      ChangeCurrentDir(startdir);
      ChangeCurrentDir(cp);
#endif
      continue;
    }
    None = 0;
    if (PrefixMatches(cp, Block.Header.name)) {
      return 1;
    }
  }
  return None;
} /* MatchesNextArg */
